﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CayleyTree
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //默认值
        int n = 10;
        double x0 = 200;
        double y0 = 310;
        double leng = 100;
        double th = -Math.PI / 2;

        private Graphics graphics;
        double th1 = 30 * Math.PI / 180;
        double th2 = 20 * Math.PI / 180;
        double per1 = 0.6;
        double per2 = 0.7;
        //定义画笔，默认颜色蓝色
        Pen pen = new Pen(Color.Blue);

        private void button1_Click(object sender, EventArgs e)
        {

            try
            {
                //获取输入参数，空则默认值
                n = int.Parse(textBox1.Text);
                leng = Convert.ToDouble(textBox2.Text);
                per1 = Convert.ToDouble(textBox3.Text);
                per2 = Convert.ToDouble(textBox4.Text);
                th1 = Convert.ToDouble(textBox5.Text) * Math.PI / 180;
                th2 = Convert.ToDouble(textBox6.Text) * Math.PI / 180;

            }
            catch
            {
                MessageBox.Show("未设置参数将使用默认值");
            }

            if (graphics == null) graphics = this.CreateGraphics();
            drawCayleyTree(n, x0, y0, leng, th, pen);
            button2.Visible = true;//清空图像按钮
        }

        void drawCayleyTree(int n,
                double x0, double y0, double leng, double th,Pen pen)
        {
            if (n == 0) return;

            double x1 = x0 + leng * Math.Cos(th);
            double y1 = y0 + leng * Math.Sin(th);

            drawLine(pen,x0, y0, x1, y1);

            drawCayleyTree(n - 1, x1, y1, per1 * leng, th + th1, pen);
            drawCayleyTree(n - 1, x1, y1, per2 * leng, th - th2, pen);
        }
        void drawLine(Pen pen, double x0, double y0, double x1, double y1)
        {

            graphics.DrawLine(
                pen,
                (int)x0, (int)y0, (int)x1, (int)y1);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                graphics.Clear(BackColor);
                button2.Visible = false;
                pen.Color = Color.Blue;
            }
            catch
            {
                MessageBox.Show("未绘制");
            }
        }

        //取色，自定义树颜色
        private void button3_Click(object sender, EventArgs e)
        {
            
            colorDialog1.ShowDialog();
            pen.Color = this.colorDialog1.Color;
        }
    }
}
